package com.fsquare.dao.paypal;

import java.util.List;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.broadleafcommerce.common.persistence.EntityConfiguration;
import org.broadleafcommerce.profile.core.domain.Customer;
import org.springframework.stereotype.Repository;

import com.fsquare.domain.paypal.PayPalPayment;

@Repository("payPalDao")
public class PayPalDaoImpl implements PayPalDao{
	
	@PersistenceContext(unitName = "blPU")
    protected EntityManager em;

    @Resource(name = "blEntityConfiguration")
    protected EntityConfiguration entityConfiguration;
    
    public PayPalPayment getPaymentById(final Long paymentId) {
        return em.find(PayPalPayment.class, paymentId);
    }

    public PayPalPayment save(PayPalPayment payPalPayment) {

    	PayPalPayment response = null;

    	if(payPalPayment.getId() == null)
    		em.persist(payPalPayment);
        else
        	em.merge(payPalPayment);
    	
        return response;
    }

    public void delete(PayPalPayment payPalPayment) {
        if (!em.contains(payPalPayment)) {
        	payPalPayment = getPaymentById(payPalPayment.getId());
        }
        em.remove(payPalPayment);
    }
    
    public PayPalPayment createPayPalPayment() {
    	PayPalPayment payPalPayment = (PayPalPayment) entityConfiguration.createEntityInstance(PayPalPayment.class.getName());
        return payPalPayment;
    }

    public PayPalPayment getPaymentsByGuid(String guid) {
    	final Query query = em.createNamedQuery("PAYPAL_PAYMENT_BY_GUID");
        query.setParameter("guid", guid);
        return (PayPalPayment)query.getSingleResult();
    }
    
    @SuppressWarnings("unchecked")
    public List<PayPalPayment> getPaymentsByCustomer(Customer customer) {
        final Query query = em.createNamedQuery("PAYPAL_PAYMENT_BY_CUSTOMER_ID");
        query.setParameter("customerId", customer.getId());
        return query.getResultList();
    }
    
    public PayPalPayment getPaymentsByPaymentId(String paymentId) {
        final Query query = em.createNamedQuery("PAYPAL_PAYMENT_BY_PAYMENT_ID");
        query.setParameter("paymentId", paymentId);
        return (PayPalPayment)query.getSingleResult();
    }
    
    @SuppressWarnings("unchecked")
	public List<PayPalPayment> getAllPayments() {
    	List<PayPalPayment> list = (List<PayPalPayment>)em.createQuery("SELECT obj FROM " + PayPalPayment.class.getSimpleName() + " obj").getResultList();
        return list;
    }

}
